import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {Unsigned8} from "./Unsigned8";
import {Buffer} from "buffer";


export class Selector9 implements AxdrType{

    dataCode : Buffer | null = null;
    recn : Unsigned8 | null = null;

    constructor() {
    }

    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(recn : Unsigned8){
        this.recn = recn;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.recn = new Unsigned8();
        this.recn.set_const();
        codeLength += this.recn.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.recn != null){
                codeLength = 0;
                codeLength += this.recn.encode(output);
            }else{
                throw new Error("recn is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.recn != null) {
            return "sequence: {"+ "recn: " + this.recn  + "}";
        } else {
            return "recn is null";
        }
    }

}
